"""
Working Fortran FFI Test - Actual ccall demonstrations

This test demonstrates WORKING Julia-Fortran integration using
a compiled shared library (.so) instead of static libraries (.a).
"""

using Test

# Path to shared library wrapper
const WRAPPER_LIB = joinpath(@__DIR__, "..", "deps", "libgsi_wrapper.so")

println("="^70)
println("Working Fortran FFI Integration Test")
println("="^70)
println("Using: $WRAPPER_LIB")
println()

@testset "Working Fortran ccall Tests" begin

    @testset "Library Availability" begin
        @test isfile(WRAPPER_LIB)
        @info "✓ Shared library found: $(basename(WRAPPER_LIB))"
    end

    @testset "Version Check" begin
        major = Ref{Int32}(0)
        minor = Ref{Int32}(0)

        ccall(
            (:gsi_wrapper_version, WRAPPER_LIB),
            Cvoid,
            (Ref{Int32}, Ref{Int32}),
            major, minor
        )

        @test major[] == 1
        @test minor[] == 0

        @info "✓ Fortran wrapper version: $(major[]).$(minor[])"
    end

    @testset "Simple Function Call" begin
        input = Int32(42)

        result = ccall(
            (:test_fortran_call, WRAPPER_LIB),
            Int32,
            (Int32,),
            input
        )

        @test result == 142  # 42 + 100

        @info "✓ test_fortran_call($input) = $result"
    end

    @testset "Array Passing - Sum" begin
        # Test zero-copy array passing
        data = Float32[1.0, 2.0, 3.0, 4.0, 5.0]
        n = Int32(length(data))

        total = ccall(
            (:fortran_array_sum, WRAPPER_LIB),
            Float32,
            (Ptr{Float32}, Int32),
            data, n
        )

        @test total ≈ 15.0f0

        @info "✓ Array sum: $(data) → $total"
    end

    @testset "Vector Dot Product" begin
        a = Float64[1.0, 2.0, 3.0, 4.0]
        b = Float64[5.0, 6.0, 7.0, 8.0]
        n = Int32(length(a))

        result = ccall(
            (:fortran_vector_dot, WRAPPER_LIB),
            Float64,
            (Ptr{Float64}, Ptr{Float64}, Int32),
            a, b, n
        )

        expected = sum(a .* b)  # 1*5 + 2*6 + 3*7 + 4*8 = 70
        @test result ≈ expected

        @info "✓ Dot product: $result (expected: $expected)"
    end

    @testset "Matrix-Vector Multiplication" begin
        # Column-major order (Fortran/Julia compatible)
        A = Float64[
            1.0 2.0 3.0;
            4.0 5.0 6.0
        ]  # 2x3 matrix

        x = Float64[1.0, 2.0, 3.0]  # 3-vector
        y = zeros(Float64, 2)        # 2-vector output

        m = Int32(size(A, 1))  # rows
        n = Int32(size(A, 2))  # cols

        ccall(
            (:fortran_matvec, WRAPPER_LIB),
            Cvoid,
            (Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Int32, Int32),
            A, x, y, m, n
        )

        # Expected: [1*1 + 2*2 + 3*3, 4*1 + 5*2 + 6*3] = [14, 32]
        expected = A * x

        @test y ≈ expected

        @info "✓ Matrix-vector: A*x = $y (expected: $expected)"
    end

    @testset "Large Array Performance" begin
        # Test with larger arrays
        n = 10000
        data = rand(Float32, n)

        total = ccall(
            (:fortran_array_sum, WRAPPER_LIB),
            Float32,
            (Ptr{Float32}, Int32),
            data, Int32(n)
        )

        expected = sum(data)
        @test total ≈ expected rtol=1e-5

        @info "✓ Large array sum (n=$n): Fortran=$total, Julia=$expected"
    end

    @testset "Memory Layout Verification" begin
        # Verify Julia and Fortran use same column-major layout
        A = Float64[
            1.0 2.0;
            3.0 4.0;
            5.0 6.0
        ]  # 3x2

        x = Float64[10.0, 20.0]
        y = zeros(Float64, 3)

        ccall(
            (:fortran_matvec, WRAPPER_LIB),
            Cvoid,
            (Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Int32, Int32),
            A, x, y, Int32(3), Int32(2)
        )

        # Manual calculation
        expected = [
            1.0*10.0 + 2.0*20.0,  # 50
            3.0*10.0 + 4.0*20.0,  # 110
            5.0*10.0 + 6.0*20.0   # 170
        ]

        @test y ≈ expected

        @info "✓ Memory layout compatible: Julia ↔ Fortran"
    end
end

println("\n" * "="^70)
println("SUCCESS: All Fortran FFI calls working!")
println("="^70)
println("\nKey Findings:")
println("1. ✓ Shared library compilation successful")
println("2. ✓ Simple scalar functions work")
println("3. ✓ Array passing (zero-copy) works")
println("4. ✓ Complex matrix operations work")
println("5. ✓ Memory layout is compatible (both column-major)")
println("6. ✓ Performance is good (large arrays)")
println("\nNext Steps:")
println("- Wrap actual GSI Fortran routines (SIGIO, CRTM)")
println("- Add error handling and status codes")
println("- Create high-level Julia interfaces")
println("- Build production-ready FFI layer")
println("="^70)
